package com.farm.project.service.impl;

import com.farm.project.domain.Field;
import com.farm.project.domain.FieldRePtype;
import com.farm.project.domain.Project;
import com.farm.project.domain.ProjectFieldins;
import com.farm.project.domain.Task;
import com.farm.project.domain.ex.ProjectField;
import com.farm.core.time.TimeTool;
import com.farm.file.WdapFileServiceInter;
import com.farm.file.domain.FileBase;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.farm.project.dao.FieldDaoInter;
import com.farm.project.dao.FieldRePtypeDaoInter;
import com.farm.project.dao.ProjectDaoInter;
import com.farm.project.dao.ProjectFieldinsDaoInter;
import com.farm.project.dao.TaskDaoInter;
import com.farm.project.service.FieldServiceInter;
import com.farm.project.service.ProjectFieldinsServiceInter;
import com.farm.web.WebUtils;
import com.sun.star.uno.RuntimeException;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：项目属性服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class ProjectFieldinsServiceImpl implements ProjectFieldinsServiceInter {
	@Resource
	private ProjectFieldinsDaoInter projectfieldinsDaoImpl;
	@Resource
	private TaskDaoInter taskDaoImpl;
	@Resource
	private ProjectDaoInter projectDaoImpl;
	@Resource
	private FieldRePtypeDaoInter fieldreptypeDaoImpl;
	@Resource
	private FieldServiceInter fieldServiceImpl;
	@Resource
	private FieldDaoInter fieldDaoImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	private static final Logger log = Logger.getLogger(ProjectFieldinsServiceImpl.class);

	@Override
	@Transactional
	public ProjectFieldins insertProjectfieldinsEntity(ProjectFieldins entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setLivetime(TimeTool.getTimeDate14());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setEuser(user.getId());
		entity.setEtime(TimeTool.getTimeDate14());
		// 1.富文本，2附件，3多行文本，4单行文本，5枚举单选，6枚举多选，7公司，8人员，9时间，10日期
		if (entity.getValtype().equals("1")) {
			throw new RuntimeException("不支持此种Valtype:" + entity.getValtype());
		}
		if (entity.getValtype().equals("2")) {
			// 支持2附件
		}
		if (entity.getValtype().equals("3")) {
			// 支持3多行文本
		}
		if (entity.getValtype().equals("4")) {
			// 支持4单行文本
		}
		if (entity.getValtype().equals("5")) {
			// 支持5枚举单选
		}
		if (entity.getValtype().equals("6")) {
			throw new RuntimeException("不支持此种Valtype:" + entity.getValtype());
		}
		if (entity.getValtype().equals("7")) {
			throw new RuntimeException("不支持此种Valtype:" + entity.getValtype());
		}
		if (entity.getValtype().equals("8")) {
			throw new RuntimeException("不支持此种Valtype:" + entity.getValtype());
		}
		if (entity.getValtype().equals("9")) {
			throw new RuntimeException("不支持此种Valtype:" + entity.getValtype());
		}
		if (entity.getValtype().equals("10")) {
			// 支持10日期
		}
		return projectfieldinsDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public ProjectFieldins editProjectfieldinsEntity(ProjectFieldins entity, LoginUser user) {
		ProjectFieldins entity2 = projectfieldinsDaoImpl.getEntity(entity.getId());
		entity2.setEuser(user.getId());
		entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setPubread(entity.getPubread());
		entity2.setEnums(entity.getEnums());
		entity2.setName(entity.getName());
		entity2.setValtype(entity.getValtype());
		entity2.setValtitle(entity.getValtitle());
		entity2.setVal(entity.getVal());
		entity2.setSingletype(entity.getSingletype());
		entity2.setSort(entity.getSort());
		entity2.setUuid(entity.getUuid());
		entity2.setLivetime(TimeTool.getTimeDate14());
		entity2.setPstate(entity.getPstate());
		projectfieldinsDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteProjectfieldinsEntity(String id, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		projectfieldinsDaoImpl.deleteEntity(projectfieldinsDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public ProjectFieldins getProjectfieldinsEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return projectfieldinsDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createProjectfieldinsSimpleQuery(DataQuery query) {
		// TODO 自动生成代码,修改后请去除本注释
		DataQuery dbQuery = DataQuery.init(query, "PLOGS_PROJECT_FIELDINS",
				"ID,HTMLDEMOID,PROJECTID,PUBREAD,ENUMS,NAME,VALTYPE,VALTITLE,VAL,PCONTENT,SORT,UUID,LIVETIME,PSTATE,ETIME,CUSER,EUSER,CTIME");
		return dbQuery;
	}

	@Override
	@Transactional
	public void loadSysField(String projectid, LoginUser currentUser) {
		// 通过项目分类id获得项目的属性
		Project project = projectDaoImpl.getEntity(projectid);
		List<FieldRePtype> fieldRes = fieldreptypeDaoImpl.selectEntitys(
				DBRuleList.getInstance().add(new DBRule("PROJECTTYPEID", project.getTypeid(), "=")).toList());
		for (FieldRePtype para : fieldRes) {
			// 属性定义
			Field field = fieldDaoImpl.getEntity(para.getFieldid());
			if (field.getPstate().equals("1")) {
				// 项目属性实例
				ProjectFieldins fieldIns = projectfieldinsDaoImpl.getOneEntityByUUID(projectid, field.getUuid());
				if (fieldIns == null) {
					fieldIns = new ProjectFieldins();
				}
				fieldIns.setPubread(para.getReadis());
				fieldIns.setValtype(field.getValtype());
				fieldIns.setName(field.getName());
				fieldIns.setEnums(field.getEnums());
				fieldIns.setUuid(field.getUuid());
				fieldIns.setSort(field.getSort());
				fieldIns.setProjectid(projectid);
				fieldIns.setPstate("1");
				fieldIns.setSingletype(field.getSingletype());
				if (fieldIns.getId() == null) {
					insertProjectfieldinsEntity(fieldIns, currentUser);
				} else {
					projectfieldinsDaoImpl.editEntity(fieldIns);
				}
			}
		}
	}

	@Override
	@Transactional
	public List<ProjectField> getAllProjectFields(String projectId, String taskid) {
		List<ProjectFieldins> fields = projectfieldinsDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("PSTATE", "1", "=")).add(new DBRule("PROJECTID", projectId, "=")).toList());
		Map<String, List<ProjectFieldins>> fieldGroups = new HashMap<>();
		for (ProjectFieldins field : fields) {
			List<ProjectFieldins> group = fieldGroups.get(field.getUuid());
			if (group == null) {
				group = new ArrayList<ProjectFieldins>();
				fieldGroups.put(field.getUuid(), group);
			}
			group.add(field);
		}
		List<ProjectField> groups = new ArrayList<>();
		for (String uuid : fieldGroups.keySet()) {
			// 是否可以在任务中阅读
			if (taskid == null || fieldServiceImpl.isReadByTask(uuid, taskid)) {
				List<ProjectFieldins> ines = fieldGroups.get(uuid);
				ProjectField pfield = null;
				for (ProjectFieldins ins : ines) {
					if (pfield == null) {
						// 首次填充属性
						pfield = new ProjectField();
						pfield.setEnums(ins.getEnums());
						pfield.setFieldines(new ArrayList<ProjectFieldins>());
						pfield.setHtmldemoid(ins.getHtmldemoid());
						pfield.setName(ins.getName());
						pfield.setProjectid(ins.getProjectid());
						pfield.setPubread(ins.getPubread());
						pfield.setSingletype(ins.getSingletype());
						pfield.setSort(ins.getSort());
						pfield.setUuid(ins.getUuid());
						pfield.setValtype(ins.getValtype());
						// 是否可以在任务中编辑
						if (taskid != null) {
							pfield.setEidtAble(fieldServiceImpl.isEditByTask(ins.getUuid(), taskid));
						} else {
							pfield.setEidtAble(true);
						}
					}
					pfield.getFieldines().add(ins);
				}
				Collections.sort(pfield.getFieldines(), new Comparator<ProjectFieldins>() {
					@Override
					public int compare(ProjectFieldins o1, ProjectFieldins o2) {
						return o1.getCtime().compareTo(o2.getCtime());
					}
				});
				groups.add(pfield);
			}
		}
		Collections.sort(groups, new Comparator<ProjectField>() {
			@Override
			public int compare(ProjectField o1, ProjectField o2) {
				return o1.getSort() - o2.getSort();
			}
		});
		return groups;
	}

	@Override
	@Transactional
	public List<ProjectField> getTaskFields(String taskId) {
		Task task = taskDaoImpl.getEntity(taskId);
		return getAllProjectFields(task.getProjectid(), taskId);
	}

	@Override
	@Transactional
	public ProjectFieldins editVal(String fieldinsId, String value, LoginUser currentUser) {
		ProjectFieldins fieldins = projectfieldinsDaoImpl.getEntity(fieldinsId);
		// 1.富文本，2附件，3多行文本，4单行文本，5枚举单选，6枚举多选，7公司，8人员，9时间，10日期
		if (fieldins.getValtype().equals("5")) {
			fieldins.setVal(value);
			fieldins.setValtitle(getEnumMap(fieldins.getEnums()).get(value));
		} else if (fieldins.getValtype().equals("2")) {
			FileBase file = wdapFileServiceImpl.getFileBase(value);
			if (file != null) {
				fieldins.setVal(value);
				fieldins.setValtitle(file.getTitle());
				try {
					wdapFileServiceImpl.submitFile(file.getId());
				} catch (FileNotFoundException e) {
					throw new RuntimeException(e.getMessage());
				}
			}
		} else {
			fieldins.setValtitle(value);
		}
		fieldins.setEtime(TimeTool.getTimeDate14());
		fieldins.setEuser(currentUser.getId());
		projectfieldinsDaoImpl.editEntity(fieldins);
		return fieldins;
	}

	/**
	 * 通过枚举项的字符串获得map字典对象
	 * 
	 * @param enums
	 * @return
	 */
	private Map<String, String> getEnumMap(String enums) {
		Map<String, String> returnMap = new HashMap<>();
		if (StringUtils.isNotBlank(enums)) {
			for (String node : WebUtils.parseIds(enums)) {
				String[] medelVal = node.split(":");
				if (medelVal.length == 2) {
					returnMap.put(medelVal[0], medelVal[1]);
				}
			}
		}
		return returnMap;
	}

	@Override
	@Transactional
	public Map<String, Object> getProjectFieldDic(String projectId) {
		List<ProjectFieldins> fields = projectfieldinsDaoImpl.selectEntitys(
				DBRuleList.getInstance().add(new DBRule("PSTATE", "1", "=")).add(new DBRule("SINGLETYPE", "1", "="))
						.add(new DBRule("VALTYPE", "2", "!=")).add(new DBRule("PROJECTID", projectId, "=")).toList());
		Map<String, Object> map = new HashMap<>();
		for (ProjectFieldins feild : fields) {
			map.put(feild.getUuid(), feild.getValtitle());
		}
		return map;
	}

	@Override
	@Transactional
	public List<ProjectFieldins> getProjectFields(String projectId) {
		List<ProjectFieldins> fields = projectfieldinsDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("PSTATE", "1", "=")).add(new DBRule("PROJECTID", projectId, "=")).toList());
		Collections.sort(fields, new Comparator<ProjectFieldins>() {
			@Override
			public int compare(ProjectFieldins o1, ProjectFieldins o2) {
				return o1.getSort() - o2.getSort();
			}
		});
		return fields;
	}

	@Override
	@Transactional
	public List<Map<String, String>> getFormatEnums(String enums) {
		List<Map<String, String>> list = new ArrayList<>();
		for (String node : WebUtils.parseIds(enums)) {
			Map<String, String> enumNode = new HashMap<>();
			String[] medelVal = node.split(":");
			if (medelVal.length == 2) {
				enumNode.put("val", medelVal[0]);
				enumNode.put("title", medelVal[1]);
				list.add(enumNode);
			}
		}
		return list;
	}

	@Override
	@Transactional
	public ProjectFieldins getProjectFieldins(String uuid, String projectid) {
		List<ProjectFieldins> fields = projectfieldinsDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("UUID", uuid, "=")).add(new DBRule("PROJECTID", projectid, "=")).toList());
		if (fields.size() > 0) {
			return fields.get(0);
		} else {
			return null;
		}
	}

	@Override
	@Transactional
	public List<ProjectFieldins> getProjectFieldines(String uuid, String projectid) {
		List<ProjectFieldins> fields = projectfieldinsDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("UUID", uuid, "=")).add(new DBRule("PROJECTID", projectid, "=")).toList());
		Collections.sort(fields, new Comparator<ProjectFieldins>() {
			@Override
			public int compare(ProjectFieldins o1, ProjectFieldins o2) {
				return o1.getCtime().compareTo(o2.getCtime());
			}
		});
		return fields;
	}

	@Override
	@Transactional
	public ProjectFieldins addFildins(Field field, String taskid, String projectid, LoginUser currentUser) {
		if (StringUtils.isNotBlank(taskid)) {
			Task task = taskDaoImpl.getEntity(taskid);
			projectid = task.getProjectid();
		}
		Project project = projectDaoImpl.getEntity(projectid);
		List<FieldRePtype> rePtype = fieldreptypeDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTTYPEID", project.getTypeid(), "="))
						.add(new DBRule("FIELDID", field.getId(), "=")).toList());
		ProjectFieldins fieldIns = new ProjectFieldins();
		if (rePtype.size() > 0) {
			fieldIns.setPubread(rePtype.get(0).getReadis());
		}
		fieldIns.setValtype(field.getValtype());
		fieldIns.setName(field.getName());
		fieldIns.setEnums(field.getEnums());
		fieldIns.setUuid(field.getUuid());
		fieldIns.setSort(field.getSort());
		fieldIns.setProjectid(projectid);
		fieldIns.setPstate("1");
		fieldIns.setSingletype(field.getSingletype());
		insertProjectfieldinsEntity(fieldIns, currentUser);
		return fieldIns;
	}

	@Override
	@Transactional
	public void deleteProjectfieldinsFromProject(String fieldInsId, String projectid, LoginUser currentUser) {
		ProjectFieldins fieldIns = getProjectfieldinsEntity(fieldInsId);
		List<ProjectFieldins> ines = getProjectFieldines(fieldIns.getUuid(), projectid);
		if (ines.size() > 0) {
			if (ines.size() > 1) {
				// 一個項目中如果有多条，就删除一条
				deleteProjectfieldinsEntity(fieldInsId, currentUser);
			} else {
				// 一個項目中如果就一条就清空值
				fieldIns.setVal(null);
				fieldIns.setValtitle(null);
				projectfieldinsDaoImpl.editEntity(fieldIns);
			}
		}
	}
}
